package comag

import (
	"fmt"
	"golang.org/x/net/context"
	"time"
)

type CoFunc func(context.Context)

func debugPrint(msg string, params ...interface{}) {
	if len(params) <= 0 {
		fmt.Println(msg)
		return
	}
	fmt.Printf(msg+"\n", params...)
}

func DemoCoA(ctx context.Context) {
	errCh := ctx.Value("error").(chan error)

	for i := 1; i <= 100; i++ {
		select {
		case <-ctx.Done():
			debugPrint("input Done by ctx: %s", ctx.Err())
			return
		default:
			if i > 10 {
				errCh <- fmt.Errorf("input error")
				return
			}
			debugPrint("input:%d", i)
			time.Sleep(time.Second)
		}
	}
}

func DemoCoB(ctx context.Context) {
	for i := 1; i <= 100; i++ {
		select {
		case <-ctx.Done():
			debugPrint("out Done by ctx: %s", ctx.Err())
			return
		default:
			debugPrint("out:%d", i)
			time.Sleep(time.Second)
		}
	}
	debugPrint("out Done")
}
